package resoft.jeasyform.core;

import resoft.jeasyform.components.Window;
import resoft.jeasyform.components.Component;
import resoft.jeasyform.util.LayoutUtil;

import java.util.Map;
import java.util.Iterator;

import charvax.swing.JPanel;
import charvax.swing.JFrame;
import charva.awt.event.KeyListener;
import charva.awt.event.KeyEvent;

/**
 * <p>to run a window</p>
 * User: albert
 * Date: Aug 30, 2007
 * Time: 1:41:54 AM
 */
public class WindowRunner {

    /**
     * load window
     *
     * @param windowName String
     * @return windowName Window
     * */
    public static Window loadWindow(String windowName) {
        return LayoutUtil.getLayoutReader().getWindow(windowName);
    }

    /**
     * open a loaded window with parameters
     *
     * @param win Window
     * @param params Map
     * */
    public static void openWindow(Window win,Map params) {
        win.setParameterMap(params);
        JPanel panel = new JPanel(null);

        //add all components
        for (Iterator itr = win.listAllComponents().iterator(); itr.hasNext();) {
            Component component = (Component) itr.next();
            component.setParentWindow(win);
            panel.add(component.getSwingObject());
        }


        JFrame frame = new JFrame();

        win.setContainer(frame);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(panel);

        //register a key,pressed ESC to exit current window
        frame.addKeyListener(new KeyListener() {


            public void keyPressed(KeyEvent ke_) {

            }

            public void keyTyped(KeyEvent keyEvent) {
                if(keyEvent.getKeyCode()==KeyEvent.VK_ESCAPE) {
                    //@todo need to modify.it should support closed event
                    System.exit(0);
                }
            }

            public void keyReleased(KeyEvent ke_) {

            }
        });
        
        frame.setSize(win.getWidth(), win.getHegith());

        win.setJFrame(frame);
        //post run windows init event
        charva.awt.EventQueue.invokeLater(new WindowInitThread(win));

        frame.show();
    }

    /**
     * read layout and open a new window
     *
     * @param windowName Windows name
     * @param params     parameter that what pass to the window
     */
    public static void openWindow(String windowName, Map params) {
        openWindow(loadWindow(windowName),params);
    }


}

class WindowInitThread implements Runnable {
    WindowInitThread(Window window) {
        this.window = window;
    }

    public void run() {
        window.invokeInitEvent();
    }

    private Window window;
}